/**
 * 
 * @author Sunix
 * @date   2013-5-19
 * @Email  SunixSky@gmail.com
 * 
 */	
package manager{
	import flash.filesystem.File;
	
	import utils.FileUtil;
	
	
	public class CategoryManager{
		
		public static var categoryArray:Array = new Array();
		public static var xml:XML;

		public static function readCategoryXML(value:XML):void{
			xml = value;
			updateCategoryArray();
		}
		
		public static function deleteXml(key:String):void{
			for each(var category:XML in xml.info){
				if(category.@key == key){
					var index:uint = category.childIndex();
					delete xml.info[index];
					var num:uint = uint(xml.@key ) -1;
					xml.@key = num;
					break;
				}
			}
			updateCategoryArray();
			writeCategoryXML();
		}
		
		public static function addXml(value:XML,key:String):void{
			xml.@key = key;
			xml.appendChild(value);
			updateCategoryArray();
			writeCategoryXML();
		}
		
		public static function editXml(value:XML,key:String):void{
			for each(var category:XML in xml.info){
				if(category.@key == key){
					var index:uint = category.childIndex();
					delete xml.info[index];
					xml.appendChild(value);
					break;
				}
			}
			updateCategoryArray();
			writeCategoryXML();
		}
		
		public static function changeNum(type:String,num:uint):void{
			for each(var category:XML in xml.info){
				if(category.@type == type){
					category.@num = num;
					break;
				}
			}
			writeCategoryXML();
		}
		
		public static function writeCategoryXML():void{
			var path:String = File.applicationDirectory.nativePath + "/assets/config/category.xml";
			FileUtil.writeXml(xml.toXMLString(),path);
		}
		
		protected static function updateCategoryArray():void{
			categoryArray = new Array();
			var i:uint = 1;
			for each(var category:XML in xml.info){
				var type:String = category.@type;
				var prefix:String = category.@prefix;
				var num:String = category.@num;
				var key:String = category.@key;
				categoryArray.push({label:type,index:i,prefix:prefix,num:num,key:key});
				i++;
			}
		}
	}
}